package Server.Expression;


import java.util.Stack;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author WIN7
 */
public  class parse {
   public static String Infix2(String input) {
    if (input == null)
        return "";
    char[] in = input.toCharArray();
    Stack<Character> stack = new Stack<Character>();
     Stack<Integer> stackNgoac = new Stack<Integer>();
    StringBuilder out = new StringBuilder();

    for (int i = 0; i < in.length; i++)
        switch (in[i]) {
//        case '&':
//        case '|': 
//            
//                out.append(' ');
//            
//        case '(':
//            int index= FindNgoac(in, i+1);
//            if(index >0)
//            {
//                stackNgoac.push(index);
//                out.append(in[i]);
//            }
//            else
//                stack.push(in[i]);
//        case ' ':
//                break;
//        case ')':
//            if(stackNgoac.empty())
//            {
//                while (!stack.empty() && stack.peek() != '(')
//                        out.append(' ').append(stack.pop());
//                if (!stack.empty())
//                        stack.pop();
//            }
//            else
//            {
//                out.append(in[i]);
//                stackNgoac.pop();
//            }
//            
//                break;
//        default:
//                out.append(in[i]);
//                break;
        case '&':
        case '|':            
            out.append(' ');
            stack.push(in[i]);
            break;
        case '(':
            int index= FindNgoac(in, i+1);
            if(index <0)
            {
                stack.push(in[i]);
                
            }
            else
            {
                stackNgoac.push(index);
                out.append(in[i]);
            }
            break;
        case ')':
            if(stackNgoac.empty())
            {
                while (!stack.empty() && stack.peek() != '(') {
                    out.append(' ');
                    out.append(stack.pop());
                }
                stack.pop();
            }
            else
            {
                out.append(in[i]);
                stackNgoac.pop();
            }
            break;
        default:
            out.append(in[i]);
            break;
        }
    
    while (!stack.isEmpty())
        out.append(' ').append(stack.pop());

    return out.toString();

}
   public static  int FindNgoac(char[] chuoi, int index)
   {
       int pos = 0;
      
       for (int i = index; i < chuoi.length; i++)
       {
           if(chuoi[i] == '&' || chuoi[i] == '|')
               return -1;
           if(chuoi[i] == '(')
               pos++;
           if(chuoi[i] == ')')
           {
               if(pos == 0)
                   return i;
               pos--;
           }
           
       }
       return -1;
   }
}
